<template>
  <!-- 面包屑 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>

  <el-card class="box-card"
           shadow="always">
    <!-- 搜索与添加 -->
    <el-row :gutter="20">
      <el-col :span="7">
        <el-input v-model="queryInfo.query"
                  placeholder="请输入内容"
                  class="input-with-select"
                  @clear="getUserList"
                  clearable>
          <template #append>
            <el-button icon="el-icon-search" @click="getUserList"></el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="addUserDialogVisible=true">添加用户</el-button>
      </el-col>
    </el-row>
    <!-- 用户列表 -->
    <el-table :data="userList"
              :border="false"
              style="width: 100%">
      <el-table-column type="index"
                       label="#"></el-table-column>
      <el-table-column prop="username"
                       label="姓名">
      </el-table-column>
      <el-table-column prop="email"
                       label="邮箱">
      </el-table-column>
      <el-table-column prop="mobile"
                       label="电话">
      </el-table-column>
      <el-table-column prop="role_name"
                       label="角色">
      </el-table-column>
      <el-table-column prop="mg_state"
                       label="状态">
        <template #default="{row}">
          <el-switch v-model="row.mg_state"
                     @change="changeState(row)"
                     active-color="#d0e6a5"
                     inactive-color="#eab0a2"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-tooltip effect="dark" content="编辑用户" placement="top" :enterable="false">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditUserDialog(row.id)" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(row.id)" circle></el-button>
          </el-tooltip>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页区 -->
    <el-pagination @current-change="changeHandler"
                   :current-page="queryInfo.pagenum"
                   :page-size="queryInfo.pagesize"
                   :pager-count="5"
                   layout="total, prev, pager, next"
                   :total="total">
    </el-pagination>
  </el-card>

  <!-- 添加用户的弹窗 -->
  <el-dialog title="添加用户"
             v-model="addUserDialogVisible"
             width="50%"
             @close="addUserDialogClose">
    <!-- 内容主体区域 -->
    <el-form ref="addFormRef"
             :model="addUserForm"
             :rules="addUserFormRules"
             label-width="70px">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="addUserForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addUserForm.password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addUserForm.email" type="email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="addUserForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <template #footer>
    <span class="dialog-footer">
      <el-button type="primary" @click="addUser">确 定</el-button>
      <el-button @click="addUserDialogVisible = false">取 消</el-button>
    </span>
    </template>
  </el-dialog>

  <!-- 修改用户的对话框 -->
  <el-dialog title="修改用户信息"
             v-model="editUserDialogVisible"
             width="50%"
             @close="editUserDialogClose">
    <el-form ref="editFormRef"
             :model="editUserForm"
             :rules="addUserFormRules"
             label-width="70px">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="editUserForm.username" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editUserForm.email" type="email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="editUserForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <template #footer>
    <span class="dialog-footer">
      <el-button type="primary" @click="editUser">确 定</el-button>
      <el-button @click="editUserDialogVisible = false">取 消</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script>
export default {
  name: 'User',
  data () {
    const checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17915)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) return cb()
      cb(new Error('请输入正确的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      addUserDialogVisible: false,
      addUserForm: {
        username: 'test',
        password: '123456',
        email: 'test@test.test',
        mobile: '13800000000'
      },
      addUserFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            max: 15,
            min: 5,
            message: '用户名在5-15个字符之间'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            max: 15,
            min: 6,
            message: '密码在6-15个字符之间'
          }
        ],
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        }, {
          type: 'email',
          message: '请输入正确的邮箱地址'
        }],
        mobile: [{
          required: true,
          message: '请输入手机号码',
          trigger: 'blur'
        },
        {
          validator: checkMobile,
          trigger: 'blur'
        }]
      },
      editUserDialogVisible: false,
      editUserForm: {},
      editUserFormRules: {
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        }, {
          type: 'email',
          message: '请输入正确的邮箱地址'
        }],
        mobile: [{
          required: true,
          message: '请输入手机号码',
          trigger: 'blur'
        },
        {
          validator: checkMobile,
          trigger: 'blur'
        }]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$axios.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    changeHandler (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async changeState (userinfo) {
      console.log(userinfo)
      const { data: res } = await this.$axios.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      console.log(res)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error(res.meta.msg)
      }
    },
    addUserDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.post('users', this.addUserForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addUserDialogVisible = false
        await this.getUserList()
      })
    },
    async showEditUserDialog (id) {
      const { data: res } = await this.$axios.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editUserForm = res.data
      console.log(this.editUserForm)
      this.editUserDialogVisible = true
    },
    editUserDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    editUser () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.put('users/' + this.editUserForm.id, {
          email: this.editUserForm.email,
          mobile: this.editUserForm.mobile
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editUserDialogVisible = false
        await this.getUserList()
      })
    },
    deleteUser (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message({ type: 'error', message: res.meta.msg })
        this.$message({ type: 'success', message: res.meta.msg })
        await this.getUserList()
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  background-color: rgb(199, 225, 212);
}

.el-table {
  margin-top: 10px;
}

/deep/ .el-table, /deep/ .el-table__expanded-cell {
  background-color: transparent;
}

/* 表格内背景颜色 */
/deep/ .el-table th,
/deep/ .el-table tr,
/deep/ .el-table td {
  background-color: transparent;
}

/deep/ .el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: rgba(0, 0, 0, 0.13);
}

/deep/ .el-pager li,
/deep/ .el-pagination .btn-next,
/deep/ .el-pagination .btn-prev {
  background-color: transparent;
  color: rgb(87, 93, 106);
}

.el-pagination {
  padding-top: 15px;
}
</style>
